const express = require('express');
const { userModel, Specialty, Doctor, ChatMessage } = require('../database/database.js');
const mongoose = require('mongoose');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

const router = express.Router();

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'Express' });
});

// GET 专业和医生数据
router.get('/api/data', async function(req, res, next) {
  try {
    const specialties = await Specialty.find();
    const doctors = await Doctor.find().populate('specialty');
    res.json({ specialties, doctors });
  } catch (err) {
    next(err);
  }
});

// GET /api/chat/history?userId=xxx&doctorId=yyy
router.get('/api/chat/history', async (req, res) => {
  const { userId, doctorId } = req.query;
  let history = [];
  try {
    history = await ChatMessage.find({
      $and: [
        {
          $or: [
            { from: userId, to: doctorId },
            { from: doctorId, to: userId }
          ]
        },
        { to: { $type: 'string' } },
        { from: { $type: 'string' } }
      ]
    }).sort({ time: 1 });
  } catch (e) {
    console.error('[ChatMessage.find] 查询历史消息失败:', e.message);
    history = [];
  }
  res.json(history);
});

// 通过 userId 查询用户信息
router.get('/api/users', async (req, res) => {
  const { userId } = req.query;
  if (!userId) {
    return res.status(400).json({ error: '缺少 userId 参数' });
  }
  if (!mongoose.Types.ObjectId.isValid(userId)) {
    return res.status(400).json({ error: 'userId 格式非法' });
  }
  try {
    let user = null;
    try {
      user = await userModel.findById(userId);
    } catch (err) {
      return res.status(500).json({ error: '数据库查询异常', detail: err.message });
    }
    if (user) {
      res.json(user);
    } else {
      res.json({ _id: userId, name: '未知客户' });
    }
  } catch (err) {
    res.status(500).json({ error: '服务器错误', detail: err.message });
  }
});

// 通过 doctorId 查询医生信息
router.get('/api/doctor', async (req, res) => {
  const { doctorId } = req.query;
  console.log('收到doctorId:', doctorId, typeof doctorId);
  if (!doctorId || !mongoose.Types.ObjectId.isValid(doctorId)) {
    return res.status(400).json({ error: 'doctorId 格式非法' });
  }
  try {
    const doctor = await Doctor.findById(doctorId);
    if (doctor) {
      res.json(doctor);
    } else {
      res.json({ _id: doctorId, name: '未知医生' });
    }
  } catch (err) {
    res.status(500).json({ error: '服务器错误' });
  }
});

// 获取所有用户
router.get('/api/users/all', async (req, res) => {
  try {
    const users = await userModel.find();
    res.json(users);
  } catch (err) {
    res.status(500).json({ error: '服务器错误' });
  }
});

// 配置multer用于音频文件上传
const upload = multer({ dest: path.join(__dirname, '../../uploads/audio') });

// 语音转文字mock函数（实际可接入百度、腾讯云等API）
async function mockSpeechToText(audioPath) {
  // 实际应调用第三方API
  return '这是语音转文字的结果';
}

// 音频上传和语音转文字接口
router.post('/api/upload/audio', upload.single('file'), async (req, res) => {
  if (!req.file) return res.status(400).json({ error: '未上传音频文件' });
  const audioPath = req.file.path;
  const audioUrl = `/uploads/audio/${path.basename(audioPath)}`;
  // 语音转文字
  let audioText = '';
  try {
    audioText = await mockSpeechToText(audioPath);
  } catch (e) {
    audioText = '';
  }
  res.json({ audioUrl, audioText });
});

// WebSocket 聊天消息存储逻辑（供 ws 服务端调用）
// 伪代码：
// if (
//   data.msgId && data.from && data.to &&
//   (data.text || data.imgUrl || data.audioUrl) &&
//   data.time && data.date
// ) {
//   await ChatMessage.create(data);
// }

module.exports = router;

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router
